/**
 * 分类管理控制器模块
 * 
 * 处理分类增删改查(CRUD)操作的业务逻辑
 */

const CategoryService = require('../services/category.service');
const CustomError = require('../utils/CustomError');
const logger = require('../utils/logger');

/**
 * 获取分类列表
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function getCategories(req, res) {
  const tree = req.query.tree === 'true';
  
  logger.debug(`获取分类列表, tree: ${tree}`);
  
  let categories;
  if (tree) {
    // 获取完整分类树
    categories = await CategoryService.getCategoryTree();
  } else {
    // 仅获取一级分类
    categories = await CategoryService.getTopLevelCategories();
  }

  res.json({
    code: 200,
    message: "获取分类列表成功",
    data: categories.map(category => category.toJSON ? category.toJSON() : category)
  });
}

/**
 * 获取单个分类详情
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function getCategoryById(req, res) {
  const id = req.params.id;

  logger.debug(`获取分类 ID: ${id}`);
  
  const category = await CategoryService.getCategoryById(id);

  if (!category) {
    throw new CustomError(404, '分类不存在');
  }
     
  res.json(
    { 
      code: 200,
      message: "获取分类信息成功",
      data: category.toJSON() 
    }
  );
}

/**
 * 获取某个分类的直接子级
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function getCategoryChildren(req, res) {
  const parentId = req.params.id;

  logger.debug(`获取分类 ${parentId} 的子级分类`);
  
  // 验证父级分类是否存在
  const parentCategory = await CategoryService.getCategoryById(parentId);
  if (!parentCategory) {
    throw new CustomError(404, '父级分类不存在');
  }

  const children = await CategoryService.getChildrenByParentId(parentId);

  res.json({
    code: 200,
    message: "获取子级分类成功",
    data: children.map(child => child.toJSON())
  });
}

/**
 * 创建新分类
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function createCategory(req, res) {
  logger.debug("创建分类");
  
  const categoryData = req.body;
  
  // 创建分类
  const category = await CategoryService.createCategory(categoryData);
  
  res.status(201).json({
    code: 201,
    message: "创建分类成功",
    data: category.toJSON()
  });
}

/**
 * 更新分类
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function updateCategory(req, res) {
  const id = req.params.id;
  const updateData = req.body;

  logger.debug(`更新分类 ID: ${id}`);
  
  const category = await CategoryService.updateCategory(id, updateData);
  
  res.json({
    code: 200,
    message: "更新分类成功",
    data: category.toJSON()
  });
}

/**
 * 删除分类
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function deleteCategory(req, res) {
  const id = req.params.id;

  logger.debug(`删除分类 ID: ${id}`);
  
  await CategoryService.deleteCategory(id);
  
  res.json({
    code: 200,
    message: "删除分类成功",
    data: null
  });
}

/**
 * 更新分类排序
 * @param {import('express').Request} req 
 * @param {import('express').Response} res 
 */
async function updateCategorySort(req, res) {
  const id = req.params.id;
  const { sortOrder } = req.body;

  logger.debug(`更新分类 ID: ${id} 的排序`);

  const category = await CategoryService.updateSortOrder(id, sortOrder);

  res.json({
    code: 200,
    message: "更新分类排序成功",
    data: category.toJSON()
  });
}

module.exports = {
  getCategories,
  getCategoryById,
  getCategoryChildren,
  createCategory,
  updateCategory,
  deleteCategory,
  updateCategorySort
};